<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="120px">
<!--      <el-form-item label="文章归属类型" prop="categoryType">-->
<!--        <el-radio-group v-model="dataForm.categoryType" @input="radioInput()">-->
<!--          <el-radio :label="0">菜单</el-radio>-->
<!--          <el-radio :label="1">文章模块</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
      <el-form-item label="文章归属" prop="categoryId">
        <div>
          <el-popover
            ref="menuListPopover"
            placement="bottom-start"
            trigger="click">
            <el-tree
              :data="menuList"
              :props="menuListTreeProps"
              node-key="id"
              ref="menuListTree"
              @current-change="menuListTreeCurrentChangeHandle"
              :default-expand-all="true"
              :highlight-current="true"
              :expand-on-click-node="false">
            </el-tree>
          </el-popover>
          <el-input v-model="dataForm.parentName" v-popover:menuListPopover :readonly="true" @clear="clearInput()"
                    placeholder="点击选择上级菜单" clearable
                    class="menu-list__input"></el-input>
        </div>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="dataForm.author" placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="信息来源" prop="infoForm">
        <el-input v-model="dataForm.infoForm" placeholder="请输入信息来源"></el-input>
      </el-form-item>
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="dataForm.type" clearable placeholder="请选择文章类型">
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content" v-if="dataForm.type===0">
        <wang-editor v-model="dataForm.content" :isClear="isClear" style="margin-bottom: 20px;"></wang-editor>
      </el-form-item>
      <el-form-item label="URL跳转" prop="url" v-if="dataForm.type===1">
        <el-input v-model="dataForm.url" placeholder="URL跳转"></el-input>
      </el-form-item>
      <el-form-item label="期刊封面" prop="coverPath" v-if="dataForm.type===2">
        <el-upload
          class="avatar-uploader"
          :headers="headers"
          :action="action"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="附件" prop="filePath">
        <el-upload
          class="upload-demo"
          :headers="headers"
          :action="action"
          :on-success="successHandler"
          multiple
          :on-exceed="handleExceed"
          :before-upload="beforeUploadHandler"
          :file-list="fileList">
          <el-button size="small" type="primary" :loading="isloading">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import WangEditor from "../../../components/wangEditor/wangEditor";
import {treeDataTranslate} from '@/utils'

export default {
  components: {
    WangEditor
  },
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        categoryId: '',
        categoryType: 0,
        title: '',
        author: '',
        infoForm: '',
        content: '',
        url: '',
        type: 0,
        coverPath: '',
        filePath: '',
        parentName: ''
      },
      dataRule: {
        categoryId: [
          {required: true, message: '文章归属不能为空', trigger: 'change'}
        ],
        title: [
          {required: true, message: '标题不能为空', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '内容不能为空', trigger: 'blur'}
        ],
        url: [
          {required: true, message: 'URL跳转不能为空', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '文章类型不能为空', trigger: 'blur'}
        ],
        coverPath: [
          {required: true, message: '封面路径不能为空', trigger: 'blur'}
        ],
      },
      isClear: false,
      typeList: [{'id': 0, 'name': '富文本'}, {'id': 1, 'name': '外链接'}, {'id': 2, 'name': '期刊'}],
      fileList: [],
      headers: {'token': this.$cookie.get("token")},
      action: this.sysConstant.FILE_UPLOAD_PATH,
      isloading: false,
      imageUrl: '',
      menuListTreeProps: {
        label: 'name',
        children: 'children'
      },
      menuList: [],
      moduleList: []
    }
  },
  methods: {
    init(id) {
      //初始化数据
      this.getParentMenuList();
      this.getModuleList()
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (!this.dataForm.id) {
          // 新增
          this.menuListTreeSetCurrentNode()
        } else {
          this.$http({
            url: this.$http.adornUrl(`/mh/content/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.categoryId = data.data.categoryId
              this.dataForm.categoryType = data.data.categoryType
              this.dataForm.title = data.data.title
              this.dataForm.author = data.data.author
              this.dataForm.infoForm = data.data.infoForm
              this.dataForm.content = data.data.content
              this.dataForm.url = data.data.url
              this.dataForm.type = data.data.type
              this.dataForm.coverPath = data.data.coverPath
              this.dataForm.filePath = data.data.filePath
              this.menuListTreeSetCurrentNode()
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/mh/content/${!this.dataForm.id ? 'save' : 'update'}`),
            method: !this.dataForm.id ? 'post' : 'put',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'categoryId': this.dataForm.categoryId,
              'categoryType':this.dataForm.categoryType,
              'title': this.dataForm.title,
              'author': this.dataForm.author,
              'infoForm': this.dataForm.infoForm,
              'content': this.dataForm.content,
              'url': this.dataForm.url,
              'type': this.dataForm.type,
              'coverPath': this.dataForm.coverPath,
              'filePath': this.dataForm.filePath,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    successHandler(res, file) {
      console.log(res)
      this.isloading = false
      this.dataForm.filePath = res.data[0].path
      this.dataForm.fileName = res.data[0].fileName
    },

    beforeUploadHandler() {
      this.isloading = true
    },

    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.imageUrl = URL.createObjectURL(file.raw);
      }

    },

    //查询父级菜单
    getParentMenuList() {
      this.$http({
        url: this.$http.adornUrl(`/mh/menu/list`),
        method: 'get',
        params: this.$http.adornParams({'status': 0})
      }).then(({data}) => {
        if (data.success) {
          let dataList = data.data
          for (let i = 0; i < dataList.length; i++) {
            if (dataList[i].parentId && dataList[i].parentId > 0) {
              for (let j = 0; j < dataList.length; j++) {
                if (dataList[j].id === dataList[i].parentId) {
                  dataList[i].parentName = dataList[j].name;
                }
              }
            }
          }
          for (let j = 0; j < dataList.length; j++) {
            if (dataList[j].parentId === '0') {
              dataList[j].parentName = "一级菜单";
            }
          }
          this.menuList = treeDataTranslate(dataList, 'id')
        }
      })
    },

    // 菜单树选中
    menuListTreeCurrentChangeHandle(data, node) {
      this.dataForm.categoryId = data.id
      this.dataForm.parentName = data.name
    },
    // 菜单树设置当前选中节点
    menuListTreeSetCurrentNode() {
      console.log(this.dataForm.categoryId)
      this.$refs.menuListTree.setCurrentKey(this.dataForm.categoryId)
      this.dataForm.parentName = (this.$refs.menuListTree.getCurrentNode() || {})['name']
      console.log(this.$refs.menuListTree)
    },

    clearInput() {
      this.dataForm.categoryId = undefined
      this.dataForm.parentName = undefined
    },

    radioInput() {
      this.dataForm.categoryId = undefined
      this.dataForm.parentName = undefined
    },

    //查询模块信息文章模块
    getModuleList() {
      this.$http({
        url: this.$http.adornUrl(`/mh/module/list`),
        method: 'get',
        params: this.$http.adornParams({'type': 2})
      }).then(({data}) => {
        if (data.success) {
          this.moduleList = data.data
        }
      })
    }

  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
